//
//  CustomSlideView.m
//  CardModeDemo
//
//  Created by apple on 16/11/22.
//  Copyright © 2016年 wenSir. All rights reserved.
//

#import "CustomSlideView.h"
#import "CardView.h"
#import "FDAlertView.h"
#import "UIImageView+WebCache.h"
#import <objc/runtime.h>
#import <WebKit/WebKit.h>
#import <CoreLocation/CoreLocation.h>

@interface CustomSlideView()<CLLocationManagerDelegate>
{
    NSMutableArray *_cardViewArray;//存储底部的cardView
    NSMutableArray *_slideCardViewArray;//存储滑动的cardView
    NSMutableArray *allCardViewArray;
    
    UIView *_bottomView;//用于显示叠加效果的底部视图
    UIScrollView *_mainScrollView;//用于滑动的交互视图
    
    NSInteger _index;//序列号
    CLLocation *currentLocation;
    NSString *currentAddress;
    NSString *destinationAddress;
}
@property (nonatomic, strong) CLLocationManager* locationManager;

@end

@implementation CustomSlideView

-(instancetype)initWithFrame:(CGRect)frame AndzMarginValue:(CGFloat)zMarginValue AndxMarginValue:(CGFloat)xMarginValue AndalphaValue:(CGFloat)alphaValue AndangleValue:(CGFloat)angleValue
{
    self = [super initWithFrame:frame];
    if (self) {
        
        [self getLocation];
        
        currentAddress = nil;
        destinationAddress = nil;
        //初始化
        self.cardDataArray = [[NSMutableArray alloc]init];
        _cardViewArray = [[NSMutableArray alloc]init];
        _slideCardViewArray = [[NSMutableArray alloc]init];
        allCardViewArray = [[NSMutableArray alloc]init];
        self.zMarginValue = zMarginValue;
        self.xMarginValue = xMarginValue;
        self.alphaValue = alphaValue;
        self.angleValue = angleValue;
        
        //设置frame
        frame.origin = CGPointMake(0, 0);
        
        //初始化两个主要视图
        _bottomView = [[UIView alloc]initWithFrame:frame];
        _bottomView.backgroundColor = [UIColor clearColor];
        _bottomView.layer.cornerRadius = 5.0;
        
        _mainScrollView = [[UIScrollView alloc]initWithFrame:frame];
        _mainScrollView.pagingEnabled = YES;
        _mainScrollView.autoresizingMask = YES;
        _mainScrollView.clipsToBounds = NO;
        _mainScrollView.showsVerticalScrollIndicator = NO;
        _mainScrollView.showsHorizontalScrollIndicator = NO;
        _mainScrollView.delegate = self;
        _mainScrollView.backgroundColor = [UIColor clearColor];
        _mainScrollView.layer.cornerRadius = 5.0;
        
        [self addSubview:_bottomView];
        [self addSubview:_mainScrollView];
        
        UIButton *closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [closeBtn setFrame:CGRectMake(self.frame.size.width/2 - 10, self.frame.size.height -20, 30, 30)];
        [closeBtn setImage:[UIImage imageNamed:@"index_close"] forState:UIControlStateNormal];
        [closeBtn addTarget:self action:@selector(removeCardView) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:closeBtn];
        
        //设置叠加视图的透视投影(这一步很重要)
        CATransform3D sublayerTransform = CATransform3DIdentity;//单位矩阵
        sublayerTransform.m34 = -0.002;
        [_bottomView.layer setSublayerTransform:sublayerTransform];
        
    }
    
    return self;
}

-(void)getLocation{
    self.locationManager = [[CLLocationManager alloc]init];
    self.locationManager.delegate = self;
    [self.locationManager requestAlwaysAuthorization];
    [self.locationManager requestWhenInUseAuthorization];
    
    //设置寻址精度
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    self.locationManager.distanceFilter = 5.0;
    [self.locationManager startUpdatingLocation];
}

-(void)goNavBtnClick:(UIButton *)sender{
    id locationDic = objc_getAssociatedObject(sender, "guideBtn");

    NSLog(@"%@",locationDic);
    
    CLGeocoder *clGeoCoder = [[CLGeocoder alloc] init];
    CLLocation *cl = [[CLLocation alloc] initWithLatitude:[locationDic[@"latitude"] floatValue] longitude:[locationDic[@"longitude"] floatValue]];
    [clGeoCoder reverseGeocodeLocation:cl completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        for (CLPlacemark *placeMark in placemarks) {
            
            destinationAddress = [NSString stringWithFormat:@"%@%@%@",placeMark.locality,placeMark.subLocality,placeMark.name];
            
            if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"iosamap://"]]) {
                // 起点为“我的位置”，终点为后台返回的坐标
                NSString *urlString = [[NSString stringWithFormat:@"iosamap://path?sourceApplication=applicationName&sid=BGVIS1&slat=%f&slon=%f&sname=%@&did=BGVIS2&dlat=%@&dlon=%@&dname=%@&dev=0&m=0&t=0",currentLocation.coordinate.latitude,currentLocation.coordinate.longitude,currentAddress,locationDic[@"latitude"],locationDic[@"longitude"],destinationAddress] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                NSURL *url = [NSURL URLWithString:urlString];
                [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:^(BOOL success) {
                    
                }];
            }else{
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"请下载高德地图" message:nil preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *actionOK = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    
                }];
                [alertController addAction:actionOK];
                [[self getCurrentVC] presentViewController:alertController animated:YES completion:nil];
            }
        }
    }];

    
//    for (UIView *view in [self getCurrentVC].view.subviews) {
//        if([view isKindOfClass: [WKWebView class]]){
//            WKWebView *wkView = (WKWebView *)view;
//            NSString *jsStr = [NSString stringWithFormat:@"setDrivingRoute('%@','%@')",locationDic[@"longitude"],locationDic[@"latitude"]];
//            NSLog(@"%@",jsStr);
//            [wkView evaluateJavaScript:jsStr completionHandler:^(id result, NSError * _Nullable error) {
//                FDAlertView *alert = (FDAlertView *)self.superview;;
//                [alert hide];
//                NSLog(@"%@----%@",result, error);
//            }];
//        }
//    }
}

-(void)goDetailBtnClick:(UIButton *)sender{
    for (UIView *view in [self getCurrentVC].view.subviews) {
        if([view isKindOfClass: [WKWebView class]]){
            WKWebView *wkView = (WKWebView *)view;
            NSString *jsStr = [NSString stringWithFormat:@"appToDetail('%@')",[NSString stringWithFormat:@"%ld",(long)sender.tag]];
            NSLog(@"%@",jsStr);
            [wkView evaluateJavaScript:jsStr completionHandler:^(id result, NSError * _Nullable error) {
                FDAlertView *alert = (FDAlertView *)self.superview;;
                [alert hide];
                NSLog(@"error----%@", error);
            }];
        }
    }
}

-(void)removeCardView
{
    FDAlertView *alert = (FDAlertView *)self.superview;;
    [alert hide];
//    [self removeFromSuperview];
//    [self getCurrentVC].view.backgroundColor = [UIColor whiteColor];
//    [self getCurrentVC].view.alpha = 1;
}

-(void)getCurrentAddress:(double)longitude Andlat:(double)latitude
{
    CLGeocoder *clGeoCoder = [[CLGeocoder alloc] init];
    CLLocation *cl = [[CLLocation alloc] initWithLatitude:latitude longitude:longitude];
    [clGeoCoder reverseGeocodeLocation:cl completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        for (CLPlacemark *placeMark in placemarks) {
            currentAddress = [NSString stringWithFormat:@"%@%@%@",placeMark.locality,placeMark.subLocality,placeMark.name];
        }
    }];
}

- (UIViewController *)getCurrentVC
{
    UIViewController *result = nil;
    
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    if (window.windowLevel != UIWindowLevelNormal)
    {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows)
        {
            if (tmpWin.windowLevel == UIWindowLevelNormal)
            {
                window = tmpWin;
                break;
            }
        }
    }
    
    UIView *frontView = [[window subviews] objectAtIndex:0];
    id nextResponder = [frontView nextResponder];
    
    if ([nextResponder isKindOfClass:[UIViewController class]])
        result = nextResponder;
    else
        result = window.rootViewController;
    
    return result;
}

-(void)addCardDataWithArray:(NSMutableArray *)array
{
    if (_cardDataArray.count == 0) {
        //初始化序列号
        _index = array.count-1;
    }
    
    [_cardDataArray addObjectsFromArray:array];
    
    if (_cardDataArray.count) {
        //加载叠加视图
        [self loadBottomView];
        //加载滚动视图
        [self loadSlideCardViewWithCount:_cardDataArray.count];
    }
}

#pragma mark- 加载最顶层的滚动视图
-(void)loadSlideCardViewWithCount:(NSInteger)count
{
    CGSize viewSize = self.frame.size;
    CGFloat width = viewSize.width; //图宽
    
    if (_cardDataArray.count>10) {
        _mainScrollView.contentSize = CGSizeMake(width, viewSize.height*_cardDataArray.count);
        
        //经过这个操作
        [_mainScrollView setContentOffset:CGPointMake(0, (count+_index)* viewSize.height) animated:NO];
    
        CardView *card = [_slideCardViewArray firstObject];
        card.frame = CGRectMake(0, _index* viewSize.height, viewSize.width, viewSize.height-58);
        
        return;
    }
    
    //坐标
    CGPoint point = CGPointMake(0, (_cardDataArray.count-1)*viewSize.height);
    
    //实例化CardView
    CardView *card = [[CardView alloc]initWithFrame:CGRectMake(point.x, point.y, viewSize.width, viewSize.height-58)];
    card.backgroundColor = [UIColor whiteColor];
    card.layer.masksToBounds = YES;
    card.layer.cornerRadius = 10.0;//设置圆角

    [card loadCardViewWithDictionary:_cardDataArray[0]];
    
    CardView *View = [[[NSBundle mainBundle]loadNibNamed:@"CardView" owner:self options:nil]objectAtIndex:0];
    View.titleLabel.text = [NSString stringWithFormat:@"%@",_cardDataArray[0][@"title"]];
    [View.imgView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",_cardDataArray[0][@"image_url"]]] placeholderImage:[UIImage imageNamed:@"WechatIMG24.jpeg"]];
    [card addSubview:View];
    View.addressLabel.text = [NSString stringWithFormat:@"%@",_cardDataArray[0][@"address"]];
    View.nintyTwoLabel.text = [NSString stringWithFormat:@"92# %@元",_cardDataArray[0][@"price_92"]];
    View.nintyFiveLabel.text = [NSString stringWithFormat:@"95# %@元",_cardDataArray[0][@"price_95"]];
    [View.guideBtn addTarget:self action:@selector(goNavBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    objc_setAssociatedObject(View.guideBtn, "guideBtn", @{@"latitude":[NSString stringWithFormat:@"%@",_cardDataArray[0][@"latitude"]],@"longitude":[NSString stringWithFormat:@"%@",_cardDataArray[0][@"longitude"]]}, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    [View.goToDetailBtn addTarget:self action:@selector(goDetailBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [View.goToDetailBtn setTag:[_cardDataArray[0][@"id"] integerValue]];
    
    //添加点击事件
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(showSelectCardViewAction)];
    [card addGestureRecognizer:tap];
    
    //添加到视图与数组中
    [_slideCardViewArray insertObject:card atIndex:0];
    [_mainScrollView addSubview:card];
    
    //设置滚动视图属性
    _mainScrollView.contentSize = _cardDataArray.count>1 ? CGSizeMake(width, viewSize.height*_cardDataArray.count):CGSizeMake(width, viewSize.height*_cardDataArray.count+1);
    _mainScrollView.contentOffset = CGPointMake(0, (_cardDataArray.count-1)* viewSize.height);
}

-(void)loadBottomView
{
    if (_cardDataArray.count>10) {
        return;
    }
    
    float width = self.frame.size.width;
    float height = self.frame.size.height;
    
    for(int i=0; i<(_cardDataArray.count<4?_cardDataArray.count:4); i++)
    {
        //设置CardView的坐标，z值和透明度
        CGPoint point = CGPointMake(0, -i*height/_xMarginValue);
        float zPosition = -i*height/_zMarginValue;
        
        //实例化CardView
        CardView *card = [[CardView alloc]initWithFrame:CGRectMake(point.x, point.y, width,height-58)];
        card.backgroundColor = [UIColor whiteColor];
        card.layer.masksToBounds = YES;
        card.layer.cornerRadius = 10.0;
        [card loadCardViewWithDictionary:_cardDataArray[i]];
        
        CardView *View = [[[NSBundle mainBundle]loadNibNamed:@"CardView" owner:self options:nil]objectAtIndex:0];
        View.titleLabel.text = [NSString stringWithFormat:@"%@",_cardDataArray[i][@"title"]];
        [View.imgView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",_cardDataArray[i][@"image_url"]]] placeholderImage:[UIImage imageNamed:@"WechatIMG24.jpeg"]];
        View.addressLabel.text = [NSString stringWithFormat:@"%@",_cardDataArray[i][@"address"]];
        View.nintyTwoLabel.text = [NSString stringWithFormat:@"92# %@元",_cardDataArray[i][@"price_92"]];
        View.nintyFiveLabel.text = [NSString stringWithFormat:@"95# %@元",_cardDataArray[i][@"price_95"]];
        [View.guideBtn addTarget:self action:@selector(goNavBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        objc_setAssociatedObject(View.guideBtn, "guideBtn", @{@"latitude":[NSString stringWithFormat:@"%@",_cardDataArray[i][@"latitude"]],@"longitude":[NSString stringWithFormat:@"%@",_cardDataArray[i][@"longitude"]]}, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        [View.goToDetailBtn addTarget:self action:@selector(goDetailBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [View.goToDetailBtn setTag:[_cardDataArray[i][@"id"] integerValue]];

        
        [card addSubview:View];
        [allCardViewArray addObject:card];
        
        if (i<3) {
            card.layer.zPosition = zPosition; // Z坐标
            card.alpha = 1;
        }
        else{
            card.layer.zPosition = -288; // Z坐标
            card.alpha = 0;
        }
        
        //添加到视图与数组中
        if(i == 0){
            card.hidden = YES;
        }
        
        [_cardViewArray insertObject:card atIndex:0];
        [_bottomView addSubview:card];
    }
}

//通过协议，告诉控制器选择的卡片
-(void)showSelectCardViewAction
{
    if([self.delegate respondsToSelector:@selector(slideCardViewDidSlectIndex:)])
    {
        [self.delegate slideCardViewDidSlectIndex:_index];
    }
    
//    NSLog(@"%ld",_index);
}

#pragma mark- UIScrollViewDelegate
- (void) scrollViewDidScroll:(UIScrollView *)scrollView //滚动时处理
{
    CGFloat offset_y = scrollView.contentOffset.y;//scrollView所在位置
    CGFloat height = scrollView.frame.size.height;//高度
    CGFloat width = scrollView.frame.size.width;//视图宽度
    CGFloat currentIndex = offset_y/height;//当前标签
    
    //得到索引
    _index = currentIndex>(int)currentIndex?(int)currentIndex+1:(int)currentIndex;
    
    if (_index>_cardDataArray.count-1) {
        _index = (int)_cardDataArray.count-1;
    }
    
    //调整滚动视图图片的角度
    CardView* scrollCardView = [_slideCardViewArray firstObject];
    
    //表示处于当前视图内
    if(scrollCardView.frame.origin.y<offset_y)
    {
        if(offset_y>_cardDataArray.count*height-height){
            scrollCardView.hidden = YES;
        }else{
            scrollCardView.hidden = NO;
            scrollCardView.frame = CGRectMake(0, _index*height, scrollCardView.frame.size.width, scrollCardView.frame.size.height);
            [scrollCardView loadCardViewWithDictionary:_cardDataArray[_cardDataArray.count-1-_index]];
            for (CardView *subView in scrollCardView.subviews) {
                subView.titleLabel.text = [NSString stringWithFormat:@"%@",_cardDataArray[_cardDataArray.count-1-_index][@"title"]];
                [subView.imgView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",_cardDataArray[_cardDataArray.count-1-_index][@"image_url"]]] placeholderImage:[UIImage imageNamed:@"WechatIMG24.jpeg"]];
                subView.addressLabel.text = [NSString stringWithFormat:@"%@",_cardDataArray[_cardDataArray.count-1-_index][@"address"]];
                subView.nintyTwoLabel.text = [NSString stringWithFormat:@"92# %@元",_cardDataArray[_cardDataArray.count-1-_index][@"price_92"]];
                subView.nintyFiveLabel.text = [NSString stringWithFormat:@"95# %@元",_cardDataArray[_cardDataArray.count-1-_index][@"price_95"]];
                [subView.guideBtn addTarget:self action:@selector(goNavBtnClick:) forControlEvents:UIControlEventTouchUpInside];
                objc_setAssociatedObject(subView.guideBtn, "guideBtn", @{@"latitude":[NSString stringWithFormat:@"%@",_cardDataArray[_cardDataArray.count-1-_index][@"latitude"]],@"longitude":[NSString stringWithFormat:@"%@",_cardDataArray[_cardDataArray.count-1-_index][@"longitude"]]}, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
                [subView.goToDetailBtn addTarget:self action:@selector(goDetailBtnClick:) forControlEvents:UIControlEventTouchUpInside];
                [subView.goToDetailBtn setTag:[_cardDataArray[_cardDataArray.count-1-_index][@"id"] integerValue]];

            }
        }
    }
    else if(scrollCardView.frame.origin.y-height<offset_y&&offset_y<=scrollCardView.frame.origin.y)
    {
        scrollCardView.hidden = NO;
    }
    else
    {
        scrollCardView.frame = CGRectMake(0, _index*height, scrollCardView.frame.size.width, scrollCardView.frame.size.height);
        [scrollCardView loadCardViewWithDictionary:_cardDataArray[_cardDataArray.count-1-_index]];
        for (CardView *subView in scrollCardView.subviews) {
            subView.titleLabel.text = [NSString stringWithFormat:@"%@",_cardDataArray[_cardDataArray.count-1-_index][@"title"]];
            [subView.imgView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",_cardDataArray[_cardDataArray.count-1-_index][@"image_url"]]] placeholderImage:[UIImage imageNamed:@"WechatIMG24.jpeg"]];
            subView.addressLabel.text = [NSString stringWithFormat:@"%@",_cardDataArray[_cardDataArray.count-1-_index][@"address"]];
            subView.nintyTwoLabel.text = [NSString stringWithFormat:@"92# %@元",_cardDataArray[_cardDataArray.count-1-_index][@"price_92"]];
            subView.nintyFiveLabel.text = [NSString stringWithFormat:@"95# %@元",_cardDataArray[_cardDataArray.count-1-_index][@"price_95"]];
            [subView.guideBtn addTarget:self action:@selector(goNavBtnClick:) forControlEvents:UIControlEventTouchUpInside];
            objc_setAssociatedObject(subView.guideBtn, "guideBtn", @{@"latitude":[NSString stringWithFormat:@"%@",_cardDataArray[_cardDataArray.count-1-_index][@"latitude"]],@"longitude":[NSString stringWithFormat:@"%@",_cardDataArray[_cardDataArray.count-1-_index][@"longitude"]]}, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
            [subView.goToDetailBtn addTarget:self action:@selector(goDetailBtnClick:) forControlEvents:UIControlEventTouchUpInside];
            [subView.goToDetailBtn setTag:[_cardDataArray[_cardDataArray.count-1-_index][@"id"] integerValue]];
        }
    }
    
    NSInteger _select = _index-3>0?(_index-3):0;
    
    for (NSInteger i=_select; i<=_index; i++) {
        //调整滚动视图图片的角度
        float currOrigin_y = i * height; //当前图片的y坐标
        
        //调整叠加视图
        CardView* moveCardView = [_cardViewArray objectAtIndex:i-_select];
        [moveCardView loadCardViewWithDictionary:_cardDataArray[_cardDataArray.count-1-i]];
        
        float range_y = (currOrigin_y - offset_y)/(_xMarginValue) ;
        
        moveCardView.frame = CGRectMake(0, range_y, width, height-58);
        
        if(range_y >= 0) // 如果超过当前滑动视图便隐藏
            moveCardView.hidden = YES;
        else
        {
            moveCardView.hidden = NO;
        }
        
        //调整弹压视图的z值
        float range_z = -(offset_y-currOrigin_y)/_zMarginValue;
        
        moveCardView.layer.zPosition = range_z;
        
        //调整弹压视图的透明度
        float alpha = 1.f + (currOrigin_y-offset_y)/_alphaValue;
        
        if (currentIndex-2<=i && i<=currentIndex) {
            moveCardView.alpha = 0.4;
        }else if(currentIndex-2>i&&currentIndex-3<i){
            moveCardView.alpha = alpha;
        }
        else{
            moveCardView.alpha = 0;
        }
    }
    
    //代理滚动时回调函数
    if([self.delegate respondsToSelector:@selector(slideCardViewDidScrollAllPage:AndIndex:)])
        [self.delegate slideCardViewDidScrollAllPage:_cardDataArray.count-1 AndIndex:_index];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    for(CardView* card in _slideCardViewArray)  //调整所有图片的z值
        card.layer.zPosition = 0;
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView //滚动结束处理
{
    if([self.delegate respondsToSelector:@selector(slideCardViewDidEndScrollIndex:)])
    {
        [self.delegate slideCardViewDidEndScrollIndex:_index];
    }
}

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    [manager stopUpdatingHeading];
    //旧址
    currentLocation = [locations lastObject];
    
    [self getCurrentAddress:currentLocation.coordinate.longitude Andlat:currentLocation.coordinate.latitude];

    //打印当前的经度与纬度
//    NSLog(@"%f,%f",currentLocation.coordinate.latitude,currentLocation.coordinate.longitude);
}

@end
